/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package com.minierp.validator;

import com.minierp.bean.ProductBean;
import com.minierp.dao.ProductDao;
import com.minierp.model.Product;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class ProductValidator implements Validator {
	private ProductDao productDao;

	public ProductDao getProductDao() {
		return this.productDao;
	}

	public void setProductDao(ProductDao productDao) {
		this.productDao = productDao;
	}

	public boolean supports(Class clazz) {
		return ProductBean.class.isAssignableFrom(clazz);
	}

	public void validate(Object obj, Errors errors) {
		ProductBean form = (ProductBean) obj;
		boolean hasError = false;
		Product d;
		if (form.getCodeRule().getGenerateRule().equals("MANUAL")
				|| form.getProduct().getId() != 0L) {
			if (form.getProduct().getProductCode() != null
					&& !form.getProduct().getProductCode().trim().equals("")) {
				d = this.productDao.get(form.getProduct().getProductCode(),
						true);
				if (d != null && d.getId() != form.getProduct().getId()) {
					errors.rejectValue("product.productCode", "", "『编号』已经存在");
					hasError = true;
				}
			} else {
				errors.rejectValue("product.productCode", "", "请输入『编号』");
				hasError = true;
			}
		}

		if (!hasError) {
			if (form.getProduct().getProductName() != null) {
				form.getProduct().setProductName(
						form.getProduct().getProductName().trim());
			}

			if (form.getProduct().getProductName() != null
					&& !form.getProduct().getProductName().equals("")) {
				d = this.productDao.getByName(form.getProduct()
						.getProductName(), true);
				if (d != null && d.getId() != form.getProduct().getId()) {
					errors.rejectValue("product.productName", "", "『品名规格』已经存在");
					hasError = true;
				}
			} else {
				hasError = true;
				errors.rejectValue("product.productName", "", "请输入『品名规格』");
			}
		}

		if (!hasError) {
			if (form.getProduct().getUnit() != null
					&& !form.getProduct().getUnit().trim().equals("")) {
				if (form.getProduct().getProductTypeId() == 0L) {
					hasError = true;
					errors.rejectValue("product.productTypeId", "", "请选择『类别』");
				} else if (form.getProduct().getMark() != null
						&& form.getProduct().getMark().length() > 200) {
					hasError = true;
					errors.rejectValue("product.mark", "", "『备注』不能超过200个字符");
				}
			} else {
				hasError = true;
				errors.rejectValue("product.unit", "", "请输入『计量单位』");
			}
		}

	}
}